<template>
  <div id="echarts" style="width: 100%;height: 100%;"></div>
</template>

<script>
import echarts from 'echarts'

export default {

  data() {
    return {
      // 左侧菜单数据
      dateData: [],
      timeData: [],
      wdData: [],
      sdData: [],
      maxWd: '',
      minWd: '',
      maxSd: '',
      minSd: '',
    }
  },
  created() {
    var that = this;
    this.queryTh();
    setTimeout(function () {
      that.echartsInit();
    }, 1000)
  },
  methods: {
    async echartsInit() {
      var chartDom = document.getElementById('echarts');
      var myChart = echarts.init(chartDom);
      var option;

      option = {
        title: {
          text: '最高温度：' + this.maxWd + '°C    最低温度：' + this.minWd + '°C    最高湿度：' + this.maxSd + '%    最低湿度：' + this.minSd + '%'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {},
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            dataView: {readOnly: false},
            magicType: {type: ['line', 'bar']},
            restore: {},
            saveAsImage: {}
          }
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: this.timeData
          },
          {
            type: 'category',
            boundaryGap: false,
            data: this.dateData
          }
        ],
        yAxis:
          [
            {
              type: 'value',
              min: 0,
              max: 100,
              axisLabel: {
                formatter: '{value} °C'
              }
            },
            {
              type: 'value',
              min: 0,
              max: 100,
              axisLabel: {
                formatter: '{value} %'
              }
            }
          ],
        series: [
          {
            name: '温度',
            type: 'line',
            showSymbol: false,
            data: this.wdData,
          },
          {
            name: '湿度',
            type: 'line',
            showSymbol: false,
            data: this.sdData,
          }
        ],
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: 90,
            end: 100,
            xAxisIndex: [0, 1]
          },
          {
            type: 'inside',
            realtime: true,
            start: 30,
            end: 100,
            xAxisIndex: [0, 1]
          }
        ],
      };
      var that = this;
      function dateFormat(fmt, date) {
        let ret;
        const opt = {
          "Y+": date.getFullYear().toString(),        // 年
          "m+": (date.getMonth() + 1).toString(),     // 月
          "d+": date.getDate().toString(),            // 日
          "H+": date.getHours().toString(),           // 时
          "M+": date.getMinutes().toString(),         // 分
          "S+": date.getSeconds().toString()          // 秒
          // 有其他格式化字符需求可以继续添加，必须转化成字符串
        };
        for (let k in opt) {
          ret = new RegExp("(" + k + ")").exec(fmt);
          if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
          };
        };
        return fmt;
      }
      setInterval(function () {
        console.log(dateFormat('HH:MM:SS',new Date()));
        that.queryTh();
        setTimeout(function (){
          myChart.setOption({
            title: {
              text: '最高温度：' + that.maxWd + '°C    最低温度：' + that.minWd + '°C    最高湿度：' + that.maxSd + '%    最低湿度：' + that.minSd + '%'
            },
            series: [
              {
                data: that.wdData,
              },
              {
                data: that.sdData,
              }
            ],
            xAxis: [
              {
                data: that.timeData
              },
              {
                data: that.dateData
              }
            ],
            yAxis: [
              {
                data: that.wdData
              },
              {
                data: that.sdData,
              }
            ],
            dataZoom: [
              {
                show: true,
                realtime: true,
                start: 90,
                end: 100,
                xAxisIndex: [0, 1]
              },
              {
                type: 'inside',
                realtime: true,
                start: 30,
                end: 100,
                xAxisIndex: [0, 1]
              }
            ],
          });
        },800)
      }, 65000);

      option && myChart.setOption(option);
    },
    async queryTh() {
      const {data: result} = await this.$http.get('/esp32/queryTh');
      this.dateData = [];
      this.timeData = [];
      this.wdData = [];
      this.sdData = [];

      for (var i = 0; i < result.data.length; i++) {
        var res = result.data[i];
        this.dateData.push(res.t_date.substring(0, 4) + '-' + res.t_date.substring(4, 6) + '-' + res.t_date.substring(6));
        this.timeData.push(res.t_time.substring(0, 2) + ':' + res.t_time.substring(2, 4));
        this.wdData.push(res.t_wd);
        this.sdData.push(res.t_sd);
      }
      this.maxWd = Math.max(...this.wdData);
      this.minWd = Math.min(...this.wdData);
      this.maxSd = Math.max(...this.sdData);
      this.minSd = Math.min(...this.sdData);
      this.dateData = [...new Set(this.dateData)];

    }
  }
}
</script>
